package org.apache.servicecomb.samples.practise.houserush.sale.api;

import org.apache.http.HttpStatus;
import org.apache.servicecomb.provider.pojo.RpcReference;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.apache.servicecomb.samples.practise.houserush.sale.aggregate.Favorite;
import org.apache.servicecomb.samples.practise.houserush.sale.aggregate.HouseOrder;
import org.apache.servicecomb.samples.practise.houserush.sale.aggregate.Sale;
import org.apache.servicecomb.samples.practise.houserush.sale.aggregate.SaleQualification;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.CustomerManageApi;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.RealestateApi;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.po.Customer;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.po.House;
import org.apache.servicecomb.samples.practise.houserush.sale.rpc.po.Realestate;
import org.apache.servicecomb.samples.practise.houserush.sale.service.HouseOrderService;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.apache.servicecomb.tracing.Span;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Snake Man
 * @system:
 * @DateTime: 2022/1/18 13:28
 * @Description:
 */
@RestSchema(schemaId = "houseOrderApiRest")
@RequestMapping("/")
public class HouseOrderApiRestImpl implements HouseOrderApi {
    //调用楼盘管理微服务接口
    @RpcReference(microserviceName = "realestate", schemaId = "realestateApiRest")
    private RealestateApi realestateApi;

    @RpcReference(microserviceName = "customer-manage", schemaId = "customerManageApiRest")
    private CustomerManageApi customerManageApi;


    @Autowired
    private HouseOrderService houseOrderService;

    /**
     * 查询所有活动，包括楼盘名称
     *
     * @return
     */
    @GetMapping("sales")
    public List<Sale> indexSales() {
        //获取所有活动
        List<Sale> sales = houseOrderService.indexSales();
        //遍历所有活动
        sales.forEach(sale -> {
            //获取楼盘id
            Integer realestateId = sale.getRealestateId();
            //根据楼盘id查询楼盘名称
            Realestate realestate = realestateApi.findRealestate(realestateId);
            //设置楼盘名字
            sale.setRealestateName(realestate.getName());
        });
        return sales;
    }

    /**
     * 查询所有活动，包括楼盘名称
     *
     * @return
     */
    @GetMapping("sales/indexAllSales")
    public List<Sale> indexAllSales() {
        return indexSales();
    }

    /**
     * 根据活动id查询活动，包括楼盘名称
     *
     * @param saleId
     * @return
     */
    @GetMapping("sales/{saleId}")
    public Sale findSale(@PathVariable(name = "saleId") int saleId) {
        return houseOrderService.findSale(saleId);
    }

    /**
     * 根据楼盘查询活动
     *
     * @param realestateId
     * @return
     */
    @GetMapping("sales/realestate/{realestateId}")
    public List<Sale> findSaleByRealestateId(@PathVariable(name = "realestateId") int realestateId) {
        return houseOrderService.findSaleByRealestateId(realestateId);
    }

    /**
     * 创建活动
     *
     * @param sale
     * @return
     */
    @PostMapping("sales")
    public Sale createSale(@RequestBody Sale sale) {
        return houseOrderService.createSale(sale);
    }

    /**
     * 活动修改
     *
     * @param saleId
     * @param sale
     * @return
     */
    @PutMapping("sales/{saleId}")
    public Sale updateSale(@PathVariable(name = "saleId") int saleId, @RequestBody Sale sale) {
        sale.setId(saleId);
        return houseOrderService.updateSale(sale);
    }

    /**
     * 删除活动
     *
     * @param saleId
     */
    //DELETE 根据id删除活动 sales/{saleId}
    @DeleteMapping("sales/{saleId}")
    public void removeSale(@PathVariable("saleId") int saleId) {
        houseOrderService.removeSale(saleId);
    }

    /**
     * 根据id查询开售活动
     *
     * @param saleId
     * @return
     */
    //GET 根据id查询开售活动，给前台客户抢房系统使用的接口 sales/order/{saleId}
    @Span
    @GetMapping("sales/order/{saleId}")
    public Sale findOrderSale(@PathVariable("saleId") int saleId) {
        return houseOrderService.findOrderSale(saleId);
    }


    /**
     * 同步修改活动资格
     *
     * @param saleQualifications
     */
    @PutMapping("sale_qualification")
    public void updateSaleQualification(@RequestBody List<SaleQualification> saleQualifications) {
        houseOrderService.updateSaleQualification(saleQualifications);
    }


    /**
     * 同步删除活动资格
     *
     * @param customerId
     */
    @DeleteMapping("sales/removeSaleQualification")
    public void removeSaleQualification(@RequestHeader int customerId) {
        houseOrderService.removeSaleQualification(customerId);
    }

    /**
     * 查询活动房源数量
     *
     * @param saleId
     * @return
     */
    @GetMapping("sales/countBySaleId/{saleId}")
    public int countHouseBySaleId(@PathVariable("saleId") int saleId) {
        return houseOrderService.countHouseBySaleId(saleId);
    }

    /**
     * 根据客户id查询收藏
     *
     * @param customerId
     * @return
     */
    @GetMapping("favorites")
    public List<Favorite> findMyFavorite(@RequestHeader("customerId") int customerId) {
        System.out.println(customerId);
        return houseOrderService.findMyFavorite(customerId);
    }

    /**
     * 客户收藏房源
     *
     * @param customerId
     * @param houseOrderId
     * @return
     */
    @PutMapping("house_orders/{houseOrderId}/add_favorite")
    public Favorite addFavorite(@RequestHeader int customerId, @PathVariable("houseOrderId") int houseOrderId) {
        return houseOrderService.addFavorite(customerId, houseOrderId);
    }

    /**
     * 根据id删除收藏
     *
     * @param customerId
     * @param id
     */
    @DeleteMapping("favorites/{id}")
    public void removeFavorite(@RequestHeader int customerId, @PathVariable("id") int id) {

        Favorite favorite = houseOrderService.findFavorite(id);

        if (favorite.getCustomerId() != customerId) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST, "", "无法删除不属于当前客户的收藏");
        }
        houseOrderService.removeFavorite(id);
    }

    /**
     * 根据房源订单id查询房源订单
     *
     * @param houseOrderId
     * @return
     */
    @GetMapping("house_orders/{houseOrderId}")
    public HouseOrder findOne(@PathVariable("houseOrderId") int houseOrderId) {
        return houseOrderService.findOne(houseOrderId);
    }

    /**
     * 根据房源id查询房源订单
     *
     * @param houseId
     * @return
     */
    @GetMapping("sales/findAllByHouseId/{houseId}")
    public HouseOrder findAllByHouseId(@PathVariable("houseId") Integer houseId) {
        return houseOrderService.findAllByHouseId(houseId);
    }

    /**
     * 根据客户id查询该客户的所有房源订单
     *
     * @param cucustomerId
     * @return
     */
    @GetMapping("sales/findAllByCustomerId")
    public List<HouseOrder> findAllByCustomerId(@RequestHeader int cucustomerId) {

        List<HouseOrder> houseOrderList = houseOrderService.findAllByCustomerId(cucustomerId);

        houseOrderList.forEach(houseOrder -> {
            houseOrder.setFavorite(null);
        });

        return houseOrderList;
    }

    /**
     * 前台首页活动查询
     *
     * @param customerId
     * @return
     */
    @GetMapping("sales/list")
    public List<Sale> indexListSales(@RequestHeader int customerId) {
        //查询活动资格
        List<SaleQualification> saleQualifications = houseOrderService.findByCustomerId(customerId);

        //声明存放活动的容器
        List<Sale> saleList = new ArrayList<>();
        //根据活动资格查询活动数据
        saleQualifications.forEach(saleQualification -> {
            //使用基于redis活动查询方法
            Sale sale = houseOrderService.findOrderSale(saleQualification.getSaleId());
            saleList.add(sale);
        });
        //返回查询的结果
        return saleList;

    }

    /**
     * 前台抢购活动详情
     *
     * @param customerId
     * @param saleId
     * @return
     */
    @GetMapping("sales/details/{saleId}")
    public List<Sale> indexDetailsSales(@RequestHeader int customerId, @PathVariable("saleId") int saleId) {
        //声明存放活动的List容器
        List<Sale> saleList = new ArrayList<>();
        //查询活动资格
        SaleQualification saleQualification = houseOrderService.findByCustomerIdAndSaleId(customerId, saleId);
        //根据活动资格的活动id 查询活动数据
        Sale sale = houseOrderService.findSale(saleQualification.getSaleId());

        //对活动数据里面的房源订单进行遍历，需要查询详情信息
        sale.getHouseOrders().forEach(houseOrder -> {
            //获取当前客户是否添加房源订单收藏
            List<Favorite> favorites = houseOrderService.findMyFavorite(customerId);

            if (favorites != null && !favorites.isEmpty()) {
                favorites.forEach(favorite -> {
                    //根据收藏信息的客户id、订单id进行判断
                    if (favorite.getCustomerId().intValue() == customerId &&
                            favorite.getHouseOrderId() == houseOrder.getId().intValue()) {
                        //如果相同，表示客户已经收藏了该房源订单，设置收藏标识
                        houseOrder.setFavorite("collect");
                    }
                });
            }
            //查询房源的详情信息，设置到房源订单中
            House house = realestateApi.findHouse(houseOrder.getHouseId());
            houseOrder.setHouseName(house.getName());
            houseOrder.setPrice(house.getPrice());
            houseOrder.setBuilDingName(house.getBuilding().getName());
        });
        //返回封装好数据的容器
        saleList.add(sale);
        return saleList;
    }

    /**
     * 后台活动订单查询
     * @return
     */
    @GetMapping("sales/indexOrderSales")
    public List<Sale> indexOrderSales() {
        //查询所有活动
        List<Sale> sales = houseOrderService.indexSales();
        //遍历活动获取数据，获取所有房源订单数据
        sales.forEach(sale -> {
            //遍历所有房源订单数据
            sale.getHouseOrders().forEach(houseOrder -> {
                try {
                    //获取客户信息
                    Customer customer = customerManageApi.findCustomer(houseOrder.getCustomerId());
                    //设置房源的客户名字和手机号码
                    if (customer != null) {
                        houseOrder.setName(customer.getName());
                        houseOrder.setPhone(customer.getPhone());
                    }

                }catch (Exception e){
                    //有异常设置为空
                    houseOrder.setName("");
                    houseOrder.setPhone("");
                }
                //根据房源id查询房源
                House house = realestateApi.findHouse(houseOrder.getHouseId());
                //根据房源id查询楼盘
                Realestate realestate = realestateApi.findRealestate(sale.getRealestateId());
                //把查询到的数据设置到房源订单中
                houseOrder.setRealestateName(realestate.getName());
                houseOrder.setHouseName(house.getName());
                houseOrder.setPrice(house.getPrice());
                houseOrder.setBuilDingName(house.getBuilding().getName());
            });
        });
        return sales;
    }

    /**
     * 活动资格查询
     * @param saleId
     * @param customerId
     * @return
     */
    @GetMapping("sales/findBySaleIdAndCustomerId/{saleId}")
    public SaleQualification findBySaleIdAndCustomerId(@PathVariable("saleId") int saleId, @RequestHeader int customerId){
        return houseOrderService.findByCustomerIdAndSaleId(customerId,saleId);
    }

    /**
     * 抢购房源
     * @param customerId
     * @param saleId
     * @param houseOrderId
     * @param orderId
     * @return
     */
    @PutMapping("house_orders/{saleId}/{houseOrderId}/{orderId}")
    public HouseOrder placeHouseOrder(@RequestHeader int customerId,
                                      @PathVariable("saleId") int saleId,
                                      @PathVariable("houseOrderId") int houseOrderId,
                                      @PathVariable("orderId") int orderId){
        return houseOrderService.placeHouseOrder(customerId,saleId,houseOrderId,orderId);
    }

    /**
     * 取消房源订单
     * @param customerId
     * @param houseOrderId
     * @param orderId
     * @return
     */
    @PutMapping("house_orders/{houseOrderId}/cancel/{orderId}")
    public HouseOrder cancelHouseOrder( @RequestHeader int customerId,
                                        @PathVariable("houseOrderId")int houseOrderId,
                                        @PathVariable("orderId") int orderId){
        return houseOrderService.cancelHouseOrder(customerId,houseOrderId,orderId);
    }
}
